
var app = getApp()
import * as Api from '../utils/api.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    model:false,
    goodsList:[],
    layList:[],
    preTotal:0,
    count:0,
    marketCount:0,
    dotCount:0,
    carInfo: [],
    winHeight:0,
    discount:0

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    console.log(app.globalData.windowHeight)
    this.getGclinkList()
    this.setData({
      winHeight: app.globalData.windowHeight-120
    })
  },
  addNew() {

    if (app.globalData.userId == null) {
      
      wx.redirectTo({
        url: '/pages/core/login/login',
      })
      return
    }

    if (!this.data.layList.length){
      wx.showToast({
        icon:"none",
        title:'请选择商品'
      })
      return
    }
    this.handleModel(this.data.layList)
    wx.navigateTo({
      url: '../example/order_list/order_list' 
    })
    
  },
  productList(e) {
    console.log(e)
    wx.navigateTo({
      url: '../example/product_datil/product_datil?id=' + e.currentTarget.dataset.item.goodsId + '&carId=' + app.globalData.carId,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  notSet(){
    return false;
  },
  remove(e){
    
    let goodsId = e.currentTarget.dataset.goodsid
    let layList = this.data.layList
    let goodsList = this.data.goodsList
    let dotCount = this.data.dotCount
    let model = this.data.model
    let count = this.data.count
    let marketCount = this.data.marketCount
    let discount = this.data.discount
    console.log(discount)
    layList.forEach((item, index) => {
      console.log(item)
      if (goodsId == item.goodsId){
        dotCount = parseInt(dotCount - item.num)
        count = parseFloat(count - item.memberPrice * item.num).toFixed(2)
        marketCount = marketCount - (item.num * item.marketPrice)
        layList.splice(index, 1)
      }
      
    })
    console.log(count)
    console.log(dotCount)

    goodsList.forEach((item, index) => {
      if (goodsId == item.goodsId) {
        item.total = item.memberPrice
        item.num = 0
      }

    })
    model = layList.length>0 ? true : false 
    discount = parseFloat(marketCount - count).toFixed(2)
    console.log(discount)
    this.setData({
      layList: layList,
      goodsList: goodsList,
      dotCount: dotCount,
      model: model,
      count: parseFloat(count),
      discount:discount,
      marketCount: marketCount
    })
  },
  reduct(e){
    console.log(e)
    console.log(e.currentTarget.dataset.num)
    if (!e.currentTarget.dataset.num){
      return
    }
    // 删除购物车 
    let discount = this.data.discount 
    let layList = this.data.layList 
    let goodsId = e.currentTarget.dataset.goodsid
    
      let data = this.data.goodsList
      let count = this.data.count
      let index = e.currentTarget.dataset.index
      let dotCount = this.data.dotCount
      let marketCount = this.data.marketCount
      
      
     
      data.forEach((item, i) => {
        if (index == i) {
          item.num = parseInt(item.num - 1)
          item.total = item.num * item.memberPrice
          console.log(count)

          console.log(item.memberPrice)
          console.log(parseFloat(count - item.memberPrice).toFixed(2))
          console.log(count - item.memberPrice)
          count = parseFloat(count - item.memberPrice).toFixed(2)
          console.log(item.marketPrice)
          console.log('卡卡')
          marketCount = parseFloat(marketCount - item.marketPrice)
          if (dotCount>0){
            dotCount = parseInt(dotCount - 1)
          }
        }
        if (item.goodsId == goodsId ){
          layList.forEach((item , index) => {
            if (item.goodsId == goodsId){
              item.num = parseInt(item.num - 1)
              console.log(item.num)
              item.total = item.num * item.memberPrice
            }
            
            
          })
        }
        layList.forEach((item, index) => {
          console.log(item.num)
          if (item.goodsId == goodsId && item.num == 0){
            layList.splice(index,1)
          }
        })
      })
      discount = parseFloat(marketCount - count).toFixed(2)
      this.setData({
        goodsList: data,
        count: parseFloat(count),
        layList:layList,
        dotCount: dotCount,
        discount: discount,
        marketCount: marketCount,
        
      })

    
    
  },
  add(e){
    let index = e.currentTarget.dataset.index
    console.log(e)
    let data = this.data.goodsList
    let preTotal = this.data.preTotal
    let count = this.data.count
    let marketCount = this.data.marketCount
    let discount = this.data.discount
    let dotCount = this.data.dotCount
    let layList = this.data.layList
    let goodsId = e.currentTarget.dataset.goodsid
    let value = e.currentTarget.dataset.value 
    let attr = layList.filter((item) => { return item.goodsId == goodsId})
    if(!attr.length){
      value.num = value.num + 1
      value.total = value.num * value.memberPrice
      layList.push(value)
      console.log(layList)
    } else{
      layList.forEach((item, i) => {
        if (goodsId == item.goodsId) {
          console.log(55)
          console.log(item.memberPrice)
          item.num = parseInt(item.num + 1)
          console.log(item.num)
          item.total = item.num * item.memberPrice
        }
      })
    }
    data.forEach((item, i) => {
      if (index == i) {
        console.log(i)
        item.num = parseInt(item.num + 1)
        dotCount = dotCount == 0 ? parseInt(dotCount + item.num) : parseInt(dotCount + 1)
        item.total = item.num * item.memberPrice
        item.totalPrice = item.num * item.marketPrice
        console.log(item.memberPrice)
        count = parseFloat(parseFloat(count) + parseFloat(item.memberPrice)).toFixed(2)
        console.log(item.marketPrice)
        console.log(count)
        console.log('啊啊')
        marketCount = parseFloat(parseFloat(marketCount) + parseFloat(item.marketPrice))
      }
    })
    discount = parseFloat(marketCount - count).toFixed(2)
    this.setData({
      goodsList: data,
      layList: layList,
      count: count,
      dotCount: dotCount,
      marketCount: marketCount,
      discount: discount
    })
  },
  addTargetCart() {
    if (app.globalData.userId == null) {
      wx.navigateTo({
        url: '/pages/core/login/login',
      })
      return
    }
    if (!this.data.layList.length) {
      wx.showToast({
        icon: "none",
        title: '请选择商品'
      })
      return
    }
    let url = app.globalData.baseUrl1 + '/shopcart/addnew'
    let data = {
      model: this.handleModel(this.data.layList),
      token: app.globalData.token,
      userId: app.globalData.userId,
      contentType: true
    }
    let callBack = (res) => {
      if (res == null) {
        console.log("网络请求错误！");
        return;
      }
      if (res.data.status != 200) {
        console.log("请求数据错误");
        return;
      }
      if (res.data.status == 200) {
        wx.showModal({
          title: '加入购物车成功',
          content: '',
          cancelText: '去购物车',
          confirmText: '继续添加',
          success: function (res) {
            if (res.confirm) {
              console.log('继续添加')
            } else if (res.cancel) {
              console.log('去购物车')
              wx.redirectTo({
                url: '/pages/core/carts/carts',
              })
            }
          }
        })
      }
    }
    Api.reqFormPost(url, data, callBack)
    
  },
  handleModel(list) {
    let attr = []
    list.forEach((item) => {
      let obj = {
        'goodsId': item.goodsId,
        'goodsNum': item.num,
        'skuId': item.skuId
      }
      attr.push(obj)
    })
    wx.setStorageSync('goodsVo', JSON.stringify(attr))
    return attr
  },
  addCart(e) {
    console.log(e)
    if (app.globalData.userId == null) {
      wx.navigateTo({
        url: '/pages/core/login/login',
      })
      return
    }
    let url = app.globalData.baseUrl1 + '/shopcart/add'
    let data = {
      token: app.globalData.token,
      userId: app.globalData.userId,
      goodsId: e.currentTarget.dataset.value.goodsId,
      skuId: e.currentTarget.dataset.value.skuId,
      num:1
    }
    let callBack = (res) => {

      if (res == null) {

        console.log("网络请求错误！");
        return;
      }

      if (res.data.status != 200) {
        console.log("请求数据错误");
        return;
      }
      if (res.data.status == 200) {
        wx.showToast({
          title: '成功',
          icon: 'success'
        })
      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  getGclinkList() {
    let self = this
    // 是否启用力洋接口
    let url = app.globalData.baseUrl1 + '/goods/front/gclinklist'
    let data = {
      carId: app.globalData.carId ? app.globalData.carId :'',
      userId: app.globalData.userId ? app.globalData.userId : '',
      merchantId: app.globalData.merchant.merchantId
    }
    //发起网络请求
    let callBack = (res) => {
      console.log(res)
      if (res == null) {
        console.log("网络请求错误！");
        return;
      }

      if (res.statusCode != 200) {
        console.log("请求数据错误");
        return;
      }
      if (res.statusCode === 200) {
        if (res.data.data.goodsDetailList && res.data.data.goodsDetailList.length>0){
          let count = 0
          let dotCount = 0
          res.data.data.goodsDetailList.forEach(item => {
            item.num = 0;
            item.total = item.num * item.memberPrice;
            item.totalPrice = item.num * item.marketPrice
            count += item.total
            dotCount += item.num
             
          })
          self.setData({
            
            goodsList: res.data.data.goodsDetailList,
            // layList: res.data.data.goodsDetailList,
            count: count,
            dotCount: dotCount
          })
          
        }
        
        console.log(self.data.goodsList)

      }
    }
    Api.reqFormPost(url, data, callBack)
  },
  showLayer(){
    if (this.data.dotCount > 0){
      this.setData({
        model: true
      })
    }
  },
  changeModel(){
    this.setData({
      model: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCarInfo()
  },
  getCarInfo() {
    let self = this
    // 是否启用力洋接口
    let url = app.globalData.baseUrl + '/bsm'
    let data = {
      modelId: app.globalData.carId ? app.globalData.carId:'',
      merchantId: app.globalData.merchant.merchantId
    }
    //发起网络请求
    let callBack = (res) => {

      if (res == null) {
        console.log("网络请求错误！");
        return;
      }

      if (res.statusCode != 200) {
        console.log("请求数据错误");
        return;
      }
      console.log(res.data.data)
      if (res.statusCode === 200) {
        self.setData({
          carInfo: res.data.data
        })

      }
    }
    Api.reqFormPost(url, data, callBack)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})